#include "stm32f10x.h"
#include "adc.h"

/**
 * 函数：ADC 初始化（PA0 -> ADC1_IN0，PA1 -> ADC1_IN1）
 * 参数：无
 * 返回值：无
 */
void adc_init(void)
{
    // 1. GPIO A0 让给 ADC1 in0，PA1 让给 ADC1 in1
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); // 开启时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);

    GPIO_InitTypeDef GPIO_InitStructure; 
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; 
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN; 
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    // 2. ADC 配置：精度
    ADC_InitTypeDef ADC_InitStructure; 
    ADC_InitStructure.ADC_Mode = ADC_Mode_Independent; 
    ADC_InitStructure.ADC_ScanConvMode = DISABLE; 
    ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; 
    ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; 
    ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None; 
    ADC_InitStructure.ADC_NbrOfChannel = 1; 
    ADC_Init(ADC1, &ADC_InitStructure); 
    
    // 3. 使能
    ADC_Cmd(ADC1, ENABLE); 
}

uint16_t adc_read(uint8_t ch)
{
    /* 选择通道：0=光敏 1=土壤 */
    uint8_t adcChannel = (ch == 0) ? ADC_Channel_0 : ADC_Channel_1;

    // 配置通道
    ADC_RegularChannelConfig(ADC1, adcChannel, 1, ADC_SampleTime_239Cycles5);

    // 开始测量
    ADC_SoftwareStartConvCmd(ADC1, ENABLE);
    // 等转换结束
    while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC));
    // return  电压值
    return ADC_GetConversionValue(ADC1); 
}
